import {defineStore} from "pinia";
import {computed, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";

// 封装购物车模块
export const useCartStore = defineStore('cart', () => {
  const user = JSON.parse(sessionStorage.getItem("CurUser"))

  // 获取购物车信息
  const cartList = ref([])

  // 获取购物车信息
  const getCartItems = async () => {
    if (user) {
      await axios.get('/dressup/cart/list', {
        params: {
          userId: user.userId
        }
      }).then(res => {
        cartList.value = res.data.data
        })
      }
    }

  // 删除商品
    const delCart = async (clNo) => {
      await axios.delete('/dressup/cart/delete', {
        params: {
          userId: user.userId,
            clNo: clNo
          }
      }).then(() => getCartItems())
    }

  // 增加商品
  const addCart = async (userId, clNo, clNum, clName, clPrice) => {
    await axios.post('/dressup/cart/add', null, {
      params: {
        userId: userId,
        clNo: clNo,
        clNum: clNum,
        clName: clName,
        clPrice: clPrice
      }
    })
        .then(response => {
          console.log('商品添加成功:', response.data);
          ElMessage.success('商品添加成功');
          getCartItems();
        })
        .catch(error => {
          console.error('添加商品失败:', error);
          ElMessage.error('商品添加失败');
        });
  }


  // 计算商品总数和总价
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.clNum, 0))
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.clNum * c.clPrice, 0))

  return {
    user,
    cartList,
    getCartItems,
    delCart,
    allCount,
    allPrice,
    addCart
  }
}, {
  persist: true
});